package com.gyms.view;

import android.animation.ObjectAnimator;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.classic.okhttp.beans.HVAreaBean;
import com.gyms.R;
import com.gyms.adapter.CommonFragmentPagerAdapter;
import com.gyms.constant.Constants;
import com.gyms.fragment.AreaFragment;
import com.gyms.view.bottomview.BaseBottomDialogFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import constant.EventConstant;
import utils.StringUtils;
import weight.CustomViewPager;
import weight.UiEvent;

/**
 * Created by ltx on 17/12/29
 */

public class TestBottomDialog extends BaseBottomDialogFragment implements View.OnClickListener {
    private ArrayList<HVAreaBean> mProviceBeans;//省数据源
    private ArrayList<HVAreaBean> mCityBeans=new ArrayList<>();//城市数据源
    private ArrayList<HVAreaBean> mDistrictsBeans=new ArrayList<>();//区域数据源

    private SparseArray<ArrayList<HVAreaBean>> mSAAreaBeans=new SparseArray<>();

    private CustomViewPager mVpArea;//底部viewpager
    private ImageView mIvCancel;

    //tabLayout
    private LinearLayout mTab;
    //处理tab点击相关
    private View mSelectedView;//选中的横线
    private int mCurSelectedPos=0;

    //选中的颜色
    private static final String S_SELCTED_COLOR="#c33055";
    private static final String S_NOM_COLOR="#333333";

    private static final String S_PROVICE="province";//代表省份
    private static final String S_CITY="city";//城市
    private static final String S_DISTRICTS="districts";//区域

    private List<String> mTags=new ArrayList<>();//三个区域的标志
    private HashMap<String ,TextView> mHMAreaTvs=new HashMap<>();//标识 为key，TextView为value

    private CommonFragmentPagerAdapter mAreasVpAdapter;

    private final static String S_Default_TEXT="请选择";

    //选择


    @Override
    public int getLayoutRes() {
        return R.layout.ll_areas_change_dialog;
    }

    @Override
    public void initListener() {
        mIvCancel.setOnClickListener(this);
        EventBus.getDefault().register(this);
        initTags();
        initTabListener();
    }

    /**
     * 初始化三个区域的标识
     */

    private void initTags() {
        mTags.add(S_PROVICE);
        mTags.add(S_CITY);
        mTags.add(S_DISTRICTS);
    }

    /**
     * 设置tab的监听事件
     */
    private void initTabListener() {
        int mChildCount=mTab.getChildCount();
        for(int i=0;i<mChildCount;i++){
            TextView mView= (TextView) mTab.getChildAt(i);
            mHMAreaTvs.put(mTags.get(i),mView);
            mView.setTag(i);
            mView.setOnClickListener(new TabViewClickListener());
        }
    }

    @Override
    public void initData() {
        Bundle mBundle=getArguments();
        if(null!=mBundle){
            mProviceBeans= (ArrayList<HVAreaBean>) mBundle.getSerializable(Constants.S_KEY_AREA_LIST);
        }
    }

    @Override
    public void initView(View mView) {
        findView(mView);
        initViewPager();
        initTabSelected(mCurSelectedPos);
        doShowAndHideTab(mCurSelectedPos);
    }

    /**
     * 初始化tab的选中的颜色
     * @param curSelectedPos 选中的位置
     */

    private void initTabSelected(int curSelectedPos) {
        int mTabCount=mTab.getChildCount();
        for(int i=0;i<mTabCount;i++){
            TextView mTv= (TextView) mTab.getChildAt(i);
            mTv.setTextColor(Color.parseColor(curSelectedPos==i?S_SELCTED_COLOR:S_NOM_COLOR));
        }
    }

    private void initViewPager() {
        List<Fragment> areaFragments = new ArrayList<>();
        AreaFragment proviceFragment = AreaFragment.newIntance(mProviceBeans, S_PROVICE);
        AreaFragment cityFragment = AreaFragment.newIntance(mCityBeans, S_CITY);
        AreaFragment districtsFragment = AreaFragment.newIntance(mDistrictsBeans, S_DISTRICTS);
        mSAAreaBeans.put(0,mProviceBeans);
        mSAAreaBeans.put(1,mCityBeans);
        mSAAreaBeans.put(2,mDistrictsBeans);
        areaFragments.add(proviceFragment);
        areaFragments.add(cityFragment);
        areaFragments.add(districtsFragment);
        mAreasVpAdapter = new CommonFragmentPagerAdapter(getChildFragmentManager(), areaFragments);
        mVpArea.setAdapter(mAreasVpAdapter);
        mVpArea.setCurrentItem(0);
        mVpArea.setOffscreenPageLimit(3);
    }

    private void findView(View mView) {
        mVpArea= (CustomViewPager) mView.findViewById(R.id.vp_area);
        mIvCancel= (ImageView)mView.findViewById(R.id.iv_close);
        mTab= (LinearLayout) mView.findViewById(R.id.ll_tab);
        mSelectedView= mView.findViewById(R.id.view_selected);
    }

    public static TestBottomDialog newInstance(ArrayList<HVAreaBean> mAreaBeans) {
        Bundle args = new Bundle();
        args.putSerializable(Constants.S_KEY_AREA_LIST, mAreaBeans);
        TestBottomDialog fragment = new TestBottomDialog();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_close:
                revertViewpager();
                dismiss();
                break;
        }
    }

    /**
     *  还原原来的状态
     */

    private void revertViewpager() {
        mVpArea.setCurrentItem(0);
        mCurSelectedPos=0;
        doShowAndHideTab(mCurSelectedPos);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    /**
     * tabView 的点击事件处理
     */

    private class TabViewClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            int pos= (int) v.getTag();
            if(mCurSelectedPos==pos){
                return;
            }
            mVpArea.setCurrentItem(pos);
            //计算底部的下划线的大小
            calculateWidth(v);
            //下划线滑动
            doMoveLine(pos,0);

        }
    }

    /**
     * 移动到具体的位置
     * @param mNextPos 下一个位置
     * @param mSpace 设置之前跟设置之后的差值
     */

    private void doMoveLine(int mNextPos,int mSpace) {
        TextView mCurView= (TextView) mTab.getChildAt(mCurSelectedPos);
        TextView mNextView= (TextView) mTab.getChildAt(mNextPos);
        ObjectAnimator.ofFloat(mSelectedView,"translationX",mCurView.getX(),mNextView.getX()+mSpace).setDuration(200).start();
        mCurSelectedPos=mNextPos;
        initTabSelected(mCurSelectedPos);
    }

    @Subscribe
    public void doShowArea(UiEvent mUiEvent){
        if(mUiEvent.getKey().equals(EventConstant.FLAG_SELECTED_AREA_BEAN)){
            HVAreaBean mSelectedBean= (HVAreaBean) mUiEvent.getObject();
            doSelectedArea(mSelectedBean);
        }
    }

    /**
     * 更换tab的状态 以及文案 并且如果所在的区不为null 就跳转下一个Fragment 否者直接返回
     * @param mSelectedBean 选中的bean
     */

    private void doSelectedArea(HVAreaBean mSelectedBean) {
        List<HVAreaBean> mTempAreaBeans=mSelectedBean.getDistricts();
        if(!StringUtils.isNull(mTempAreaBeans)){//不为null 跳转到下一级
            String mTempTag=mSelectedBean.mTag;//获取到当前的tag
             //设置tab 文本
            TextView mCurTv=mHMAreaTvs.get(mTempTag);
            int mPreTvWidth=getViewWidth(mCurTv);//setText之前
            //解决第一次setText 之后getx()没有立即生效
            mCurTv.setText(mSelectedBean.name);
            int mAfterWidth=getViewWidth(mCurTv);//setText之后
            int mSpace=mAfterWidth-mPreTvWidth;
            //横线滑动到下一个位置
            int mNextPos=getNextPosByTag(mTempTag);
            //隐藏除当前位置之外的view，显示当前的view
            doShowAndHideTab(mNextPos);
            doMoveLine(mNextPos,mSpace);
            //展示下一个Fragment
            mAreasVpAdapter.update(mCurSelectedPos,mTempAreaBeans);
            mVpArea.setCurrentItem(mCurSelectedPos);
            //设置下一个底部选中的下划线的大小
            View mNextView=mTab.getChildAt(mCurSelectedPos);
            calculateWidth(mNextView);
        }else{//直接返回值
            TextView mCurTextView= (TextView) mTab.getChildAt(mCurSelectedPos);
            mCurTextView.setText(mSelectedBean.name);
            revertViewpager();
            dismiss();
        }
    }

    /**
     * 隐藏当前pos之外的view ，显示当前的pos之前的view
     */

    private void doShowAndHideTab(int mCurPosition) {
        int mTabCount=mTab.getChildCount();
        for(int i=0;i<mTabCount;i++){
            View mView=mTab.getChildAt(i);
            mView.setVisibility(i<=mCurPosition?View.VISIBLE:View.INVISIBLE);
        }
        TextView mCurTextView= (TextView) mTab.getChildAt(mCurPosition);
        mCurTextView.setText(S_Default_TEXT);
    }

    /**
     * 根据tag 获取到下一个移动的位置 对应的tv以及Fragment
     * @param mTag tag
     */

    private int getNextPosByTag(String mTag) {
        for(int i=0;i<mTags.size();i++){
            String mTempTag=mTags.get(i);
            if(mTempTag.equals(mTag)){
                return i+1;
            }
        }
        return 0;
    }

    /**
     * 计算当前view 的大小 并设置给底部的下划线
     * @param mView tabView
     */

    private void calculateWidth(View mView){
        RelativeLayout.LayoutParams mLPSelected= (RelativeLayout.LayoutParams) mSelectedView.getLayoutParams();
        mLPSelected.width= getViewWidth(mView);
        mSelectedView.setLayoutParams(mLPSelected);
    }

    /**
     * 测量一个view 的宽度
     * @param mView mView
     * @return view的宽度
     */
    private int getViewWidth(View mView){
        int widthSpec =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
        int heightSpec =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
        mView.measure(widthSpec,heightSpec);
        return mView.getMeasuredWidth();
    }
}
